package com.example.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.CreateOrderRequest;
import com.example.mapper.OrderMapper;
import com.example.mq.sender.IMsgSender;
import com.example.po.OrderPO;
import com.example.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements OrderService {

    @Autowired
    private IMsgSender msgSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(CreateOrderRequest req)
    {
        OrderPO orderPO = new OrderPO();
        orderPO.setId(IdUtil.fastSimpleUUID());
        orderPO.setGoods(req.getGoods());
        orderPO.setPrice(req.getPrice());
        this.save(orderPO);

        log.info("投递订单消息");
        if (req.getDelaySeconds() == 0)
        {
            // 投递订单消息（立即投递）
            this.msgSender.send(orderPO);
        }
        else
        {
            // 投递订单消息（延迟投递）
            this.msgSender.send(req.getDelaySeconds(), TimeUnit.SECONDS, orderPO);
        }

        return orderPO.getId();
    }

}
